package com.kmxd.ams.controller.oss;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kmxd.ams.client.oss.IEfileRecordSvc;
import com.kmxd.ams.client.oss.dto.EfileRecordDTO;
import com.kmxd.ams.client.oss.dto.EfileRecordEditDTO;
import com.kmxd.ams.client.oss.dto.EfileRecordQueryDTO;
import com.kmxd.ams.client.oss.dto.EfileSortDTO;
import com.kmxd.ams.client.oss.vo.EfileRecordListVO;
import com.kmxd.ams.client.oss.vo.EfileRecordVO;
import com.kmxd.ams.core.common.constant.ErrorCode;
import com.kmxd.ams.core.common.enums.ArchOpEnum;
import com.kmxd.ams.core.common.enums.LogLevelEnum;
import com.kmxd.ams.core.common.enums.LogTypeEnum;
import com.kmxd.ams.core.exception.BizTipException;
import com.kmxd.ams.core.log.annotation.ArchLogParameter;
import com.kmxd.ams.core.log.annotation.AutoLog;
import com.kmxd.ams.core.oss.bo.OssFile;
import com.kmxd.ams.core.oss.template.OssTemplate;
import com.kmxd.ams.core.result.R;
import com.kmxd.ams.core.result.ResultCode;
import com.kmxd.ams.core.util.SecurityUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 电子文件表 前端控制器
 *
 * @author ZuoLG
 * @since 2022-07-25
 */
@RestController
@Tag(name = "电子文件表")
@RequestMapping("/oss/efileRecord")
@AllArgsConstructor
@Slf4j
public class EfileRecordCtl {

  private IEfileRecordSvc efileRecordService;

  @Autowired private OssTemplate ossTemplate;

  /** 分页查询 */
  @Operation(summary = "分页查询")
  @GetMapping("/selectPage")
  @AutoLog(
      module = "电子文件表",
      type = LogTypeEnum.ELECTRONIC_RECORD,
      level = LogLevelEnum.LOW,
      title = "分页查询",
      opType = "分页查询")
  public R<Page<EfileRecordListVO>> selectPage(Page reqPage, EfileRecordQueryDTO req) {
    return R.success(efileRecordService.selectPage(reqPage, req));
  }

  /** 列表查询 */
  @Operation(summary = "列表查询")
  @GetMapping("/selectList")
  @AutoLog(
      module = "电子文件表",
      type = LogTypeEnum.ELECTRONIC_RECORD,
      level = LogLevelEnum.LOW,
      title = "列表查询",
      opType = "列表查询")
  public R<List<EfileRecordListVO>> selectList(EfileRecordQueryDTO req) {
    return R.success(efileRecordService.selectList(req));
  }

  @SneakyThrows
  @Operation(summary = "文件上传")
  @PostMapping("/upload")
  @SaCheckPermission("oss:efileRecord:add")
  @AutoLog(
      module = "电子文件表",
      type = LogTypeEnum.ELECTRONIC_RECORD,
      level = LogLevelEnum.HIGH,
      title = "文件上传",
      opType = "挂载")
  @ArchLogParameter(op = ArchOpEnum.UPLOAD, content = "挂接电子文件")
  public R<EfileRecordVO> upload(
      @RequestParam("file") MultipartFile file,
      @RequestParam("archTypeId") Long archTypeId,
      @RequestParam("archId") Long archId,
      @RequestParam("tableId") String tableId,
      @RequestParam("archCode") String archCode,
      @RequestParam("fondsCode") String fondsCode) {
    if (Objects.isNull(file)) {
      throw BizTipException.instance(ErrorCode.EXCEPTION, ResultCode.PARAM_MISS.getMessage());
    }
    EfileRecordDTO recordDTO = new EfileRecordDTO();
    recordDTO.setArchId(archId);
    recordDTO.setArchCode(archCode);
    recordDTO.setTableId(tableId);
    recordDTO.setArchTypeId(archTypeId);
    recordDTO.setFondsCode(
        ObjectUtil.isNotEmpty(fondsCode) ? fondsCode : SecurityUtil.getFondsCode());
    return R.success(efileRecordService.upload(file, recordDTO));
  }

  /** 修改 */
  @Operation(summary = "修改")
  @PostMapping("/edit")
  @SaCheckPermission("oss:efileRecord:edit")
  @AutoLog(
      module = "电子文件表",
      type = LogTypeEnum.ELECTRONIC_RECORD,
      level = LogLevelEnum.HIGH,
      title = "修改",
      opType = "编辑")
  public R<Void> edit(@Validated @RequestBody EfileRecordEditDTO req) {
    efileRecordService.edit(req);
    return R.success();
  }

  /** 删除 */
  @Operation(summary = "删除")
  @PostMapping("/remove")
  @SaCheckPermission("oss:efileRecord:remove")
  @AutoLog(
      module = "电子文件表",
      type = LogTypeEnum.ELECTRONIC_RECORD,
      level = LogLevelEnum.HIGH_RISK,
      title = "删除",
      opType = "删除")
  public R<Void> remove(@RequestParam String ids) {
    efileRecordService.remove(ids);
    return R.success();
  }

  /** 查看 */
  @Operation(summary = "查看")
  @GetMapping("/view")
  @AutoLog(
      module = "电子文件表",
      type = LogTypeEnum.ELECTRONIC_RECORD,
      level = LogLevelEnum.LOW,
      title = "查看",
      opType = "浏览")
  public R<EfileRecordVO> view(@RequestParam Long id) {
    return R.success(efileRecordService.view(id));
  }

  /** 文件下载 */
  @Operation(summary = "文件下载")
  @GetMapping("/download")
  @AutoLog(
      module = "文件下载",
      type = LogTypeEnum.ELECTRONIC_RECORD,
      level = LogLevelEnum.HIGH,
      title = "文件下载",
      opType = "下载")
  @SneakyThrows
  @SaCheckPermission("oss:efileRecord:download")
  public void download(Long id, HttpServletResponse response) {
    EfileRecordVO recordVO = efileRecordService.view(id);
    response.reset();
    response.setContentType("application/octet-stream;charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
    response.setHeader(
        "Content-Disposition",
        "attachment; filename="
            + URLEncoder.encode(recordVO.getTitle(), StandardCharsets.UTF_8.name()));
    response.addHeader("Content-Length", String.valueOf(recordVO.getFile().length()));
    try (ServletOutputStream out = response.getOutputStream()) {
      IoUtil.write(out, true, FileUtil.readBytes(recordVO.getFile()));
    } catch (IOException e) {
      log.error("{} 文件下载失败", recordVO, e);
    }
  }

  /** 修改排序 */
  @Operation(summary = "修改排序")
  @PostMapping("/updateSort")
  @SaCheckPermission("oss:efileRecord:updateSort")
  @AutoLog(
      module = "门类配置-元数据",
      type = LogTypeEnum.ELECTRONIC_RECORD,
      level = LogLevelEnum.HIGH,
      title = "修改排序",
      opType = "编辑")
  public R<Void> updateSort(@Validated @RequestBody EfileSortDTO req) {
    efileRecordService.updateSort(req);
    return R.success();
  }

  /** 验证电子文件md5 */
  @Operation(summary = "验证电子文件md5")
  @PostMapping("/efileMd5Check")
  @AutoLog(
      module = "门类配置-元数据",
      type = LogTypeEnum.ELECTRONIC_RECORD,
      level = LogLevelEnum.HIGH,
      title = "验证电子文件md5",
      opType = "验证")
  public R<Void> efileMd5Check(@Validated @RequestBody EfileRecordEditDTO req) {
    efileRecordService.efileMd5Check(req);
    return R.success();
  }

  /** 批量下载电子文件 */
  @Operation(summary = "批量下载电子文件")
  @GetMapping("/exportBatch")
  @SaCheckPermission("oss:efileRecord:export")
  @AutoLog(
      module = "电子文件表",
      type = LogTypeEnum.ELECTRONIC_RECORD,
      level = LogLevelEnum.HIGH,
      title = "批量下载电子文件",
      opType = "下载")
  @SneakyThrows
  public void exportBatch(
      @RequestParam String ids, String docIds, String volIds, HttpServletResponse response) {
    OssFile ossFile = efileRecordService.exportBatch(ids, docIds, volIds);
    if (ObjectUtil.isNotNull(ossFile)) {
      response.reset();
      response.setContentType("application/octet-stream;charset=UTF-8");
      response.setCharacterEncoding("UTF-8");
      response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
      response.setHeader(
          "Content-Disposition",
          "attachment; filename="
              + URLEncoder.encode(ossFile.getName(), StandardCharsets.UTF_8.name()));
      response.addHeader("Content-Length", String.valueOf(ossFile.getFile().length()));
      try (ServletOutputStream out = response.getOutputStream()) {
        IoUtil.write(out, true, FileUtil.readBytes(ossFile.getFile()));
      } catch (IOException e) {
        log.error("{} 文件下载失败", ossFile, e);
      }
    }
  }

  /** 导出Zip包 */
  @Operation(summary = "导出Zip包")
  @GetMapping("/exportZip")
  @SaCheckPermission("oss:efileRecord:export")
  @AutoLog(
      module = "电子文件表",
      type = LogTypeEnum.ELECTRONIC_RECORD,
      level = LogLevelEnum.HIGH,
      title = "导出Zip包",
      opType = "下载")
  @SneakyThrows
  public void exportZip(EfileRecordQueryDTO req, HttpServletResponse response) {
    OssFile ossFile = efileRecordService.exportZip(req);
    if (ObjectUtil.isEmpty(ossFile)
        || ObjectUtil.isEmpty(ossFile.getFile())
        || ossFile.getFile().length() == 0) {
      throw BizTipException.instance(ErrorCode.E_FILE_NOT_MOUNT, "当前所选档案电子文件未找到!");
    }
    if (ObjectUtil.isNotNull(ossFile)) {
      response.reset();
      response.setContentType("application/octet-stream;charset=UTF-8");
      response.setCharacterEncoding("UTF-8");
      response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
      response.setHeader(
          "Content-Disposition",
          "attachment; filename="
              + URLEncoder.encode(ossFile.getName(), StandardCharsets.UTF_8.name()));
      response.addHeader("Content-Length", String.valueOf(ossFile.getFile().length()));
      try (ServletOutputStream out = response.getOutputStream()) {
        IoUtil.write(out, true, FileUtil.readBytes(ossFile.getFile()));
      } catch (IOException e) {
        log.error("{} 文件下载失败", ossFile, e);
      }
    }
  }

  /** 预览 */
  @SneakyThrows
  @Operation(summary = "预览")
  @GetMapping("/preview")
  @AutoLog(module = "电子文件表", title = "预览", opType = "浏览")
  public void preview(
      @RequestParam(required = false) Long id,
      @RequestParam(required = false) Integer type,
      HttpServletResponse response) {
    if (ObjectUtil.isEmpty(id)) {
      return;
    }
    if (ObjectUtil.isNotEmpty(id)) {

      EfileRecordVO efileRecordVO =
          Optional.ofNullable(efileRecordService.pdfPreview(id, type))
              .orElseThrow(() -> BizTipException.instance(ErrorCode.NOT_FOUND, "电子文件不存在!"));
      if (Objects.isNull(efileRecordVO.getShowFilePath())) {
        BizTipException.throwException(ErrorCode.E_FILE_NOT_MOUNT, "电子文件不存在!");
      }
      if (!FileUtil.exist(efileRecordVO.getFile())) {
        BizTipException.throwException(ErrorCode.E_FILE_NOT_CONVERT, "文件未转换");
      }
      String filename = efileRecordVO.getSaveFileName();
      response.setContentType("application/pdf");
      response.setCharacterEncoding("UTF-8");
      response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
      response.setHeader(
          "Content-Disposition",
          "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name()));
      FileUtil.writeToStream(efileRecordVO.getFile(), response.getOutputStream());
    }
  }
}
